package com.quktzhuanka.app;

import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.NotificationManagerCompat;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RadioButton;

import com.google.gson.Gson;
import com.jd.open.api.sdk.DefaultJdClient;
import com.jd.open.api.sdk.JdClient;
import com.jd.open.api.sdk.JdException;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.quktzhuanka.app.activity.WebViewActivityz;
import com.uuch.adlibrary.AdConstant;
import com.uuch.adlibrary.AdManager;
import com.uuch.adlibrary.bean.AdInfo;
import com.quktzhuanka.app.activity.JdDetailsActivity;
import com.quktzhuanka.app.activity.PddDetailsActivity;
import com.quktzhuanka.app.activity.PromotionDetailsActivity;
import com.quktzhuanka.app.activity.QdActivity;
import com.quktzhuanka.app.activity.WebViewActivity;
import com.quktzhuanka.app.activity.WebViewActivity2;
import com.quktzhuanka.app.activity.WebViewActivity3;
import com.quktzhuanka.app.base.BaseActivity;
import com.quktzhuanka.app.bean.JdGoodsResp;
import com.quktzhuanka.app.bean.MessageEvent;
import com.quktzhuanka.app.bean.PDDBean;
import com.quktzhuanka.app.bean.PddClient;
import com.quktzhuanka.app.bean.UserBean;
import com.quktzhuanka.app.bean.UserInfoBean;
import com.quktzhuanka.app.common.ACache;
import com.quktzhuanka.app.common.SPUtils;
import com.quktzhuanka.app.common.T;
import com.quktzhuanka.app.config.Constants;
import com.quktzhuanka.app.config.TTAdManagerHolder;
import com.quktzhuanka.app.fragments.CommuitityFragment;
import com.quktzhuanka.app.fragments.HkFragment;
import com.quktzhuanka.app.fragments.HomeFragment;
import com.quktzhuanka.app.fragments.KindFragment;
import com.quktzhuanka.app.fragments.MyFragment;
import com.quktzhuanka.app.fragments.VIPFragment;
import com.quktzhuanka.app.fragments.YXFragment;
import com.quktzhuanka.app.https.HttpUtils;
import com.quktzhuanka.app.login.WelActivity;
import com.quktzhuanka.app.my.BalanceActivity;
import com.quktzhuanka.app.my.MyOrderActivity;
import com.quktzhuanka.app.widget.CaiNiaoRadioGroup;
import com.youth.banner.transformer.ZoomOutTranformer;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import cz.msebera.android.httpclient.Header;
import jd.union.open.goods.query.request.GoodsReq;
import jd.union.open.goods.query.request.UnionOpenGoodsQueryRequest;
import jd.union.open.goods.query.response.UnionOpenGoodsQueryResponse;

/**
 * Created by yohn on 2018/7/11.
 */

public class MainActivity extends BaseActivity {
    private FragmentManager fm;
    @BindView(R.id.rg)
    CaiNiaoRadioGroup rg;
//    @BindView(R.id.rb_1)
//    RadioButton rb_1;
//    @BindView(R.id.rb_2)
//    RadioButton rb_2;
//    @BindView(R.id.rb_3)
//    RadioButton rb_3;
//    @BindView(R.id.rb_4)
//    RadioButton rb_4;
//    @BindView(R.id.rb_5)
//    RadioButton rb_5;
    int type = 0;//登录成功后跳转到我的
    private ACache mAcache;
    private String token, phone, pwd;
//    private Fragment indexFragment, kindFragment, vipFragment, commuitiyFragment, myFragment;
    private List<AdInfo> adInfos = new ArrayList<>();
    AdManager adManager;
    private int currentAc = 0;
    private Fragment f1, f2, f3, f4, f5;
    //    private FragmentManager fm;
    FragmentTransaction ft;
    private Fragment currentFragment = new Fragment();
    @Override
    protected void initUI() {
//        if (Build.VERSION.SDK_INT >= 21) {
//            View decorView = getWindow().getDecorView();
//            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
//            getWindow().setStatusBarColor(Color.TRANSPARENT);
//        }
        setContentView(R.layout.ac_main);
        ButterKnife.bind(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (adManager == null && !"".equals(SPUtils.getStringData(this, Constants.TOKEN, ""))) {
            getActivities();
        }

        checkVersion();
        EventBus.getDefault().register(this);
        NotificationManagerCompat notification = NotificationManagerCompat.from(this);
        boolean isEnabled = notification.areNotificationsEnabled();
        if (!isEnabled) {
            //未打开通知
            AlertDialog alertDialog = new AlertDialog.Builder(this)
                    .setTitle("提示")
                    .setCancelable(false)
                    .setMessage("“通知”中打开通知权限可以及时获取查看订单消息哦")
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    })
                    .setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                            Intent intent = new Intent();
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                                intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
                                intent.putExtra("android.provider.extra.APP_PACKAGE", getPackageName());
                            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {  //5.0
                                intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
                                intent.putExtra("app_package", getPackageName());
                                intent.putExtra("app_uid", getApplicationInfo().uid);
                                startActivity(intent);
                            } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {  //4.4
                                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                intent.addCategory(Intent.CATEGORY_DEFAULT);
                                intent.setData(Uri.parse("package:" + getPackageName()));
                            } else if (Build.VERSION.SDK_INT >= 15) {
                                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                                intent.setData(Uri.fromParts("package", getPackageName(), null));
                            }
                            startActivity(intent);

                        }
                    })
                    .create();
            alertDialog.show();
            alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(Color.BLACK);
            alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.colorPrimary));
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        getRate();
        JPushInterface.setAlias(this, SPUtils.getStringData(this, Constants.UID, ""),
                new TagAliasCallback() {//回调接口,i=0表示成功,其它设置失败
                    @Override
                    public void gotResult(int responseCode, String s, Set<String> set) {
                        if (responseCode == 0) {
                            System.out.println("jpush alias@@@@@别名设置成功");
                        }
                    }
                });
        /**
         * 在这边判断是不是点击通知栏进入
         * 点击通知栏的话，根据通知类型做相应的跳转
         */
        if ("order".equals(SPUtils.getStringData(this, "inform_title", "-1"))) {
            SPUtils.saveStringData(this, "inform_title", "-1");
            Intent intent = new Intent(this, MyOrderActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            startActivity(intent);
        } else if ("banlance".equals(SPUtils.getStringData(this, "inform_title", "-1"))) {
            SPUtils.saveStringData(this, "inform_title", "-1");
            UserInfoBean userBean = CaiNiaoApplication.getUserInfoBean();
            Bundle b = new Bundle();
            if (null != userBean && null != userBean.user_msg) {
                b.putString("balance", userBean.user_msg.balance);
                b.putString("user", userBean.user_msg.balance_user);
                b.putString("service", userBean.user_msg.balance_service);
                b.putString("plantform", userBean.user_msg.balance_plantform);
            }
            Intent intent = new Intent(this, BalanceActivity.class);
            intent.putExtras(b);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            startActivity(intent);
        } else if ("goods".equals(SPUtils.getStringData(this, "inform_title", "-1"))) {
            SPUtils.saveStringData(this, "inform_title", "-1");
            if (SPUtils.getStringData(this, "inform_message", "-1").startsWith("taobao")) {
                Bundle bundle = new Bundle();
                bundle.putString("num_iid", SPUtils.getStringData(this, "inform_message", "-1").substring(7));
                openActivity(PromotionDetailsActivity.class, bundle);
            } else if (SPUtils.getStringData(this, "inform_message", "-1").startsWith("jingdong")) {
                getJdGoodsMsgRequest(SPUtils.getStringData(this, "inform_message", "-1").substring(9));
            } else if (SPUtils.getStringData(this, "inform_message", "-1").startsWith("pdd")) {
                getPddGoodsMsgRequest(SPUtils.getStringData(this, "inform_message", "-1").substring(4));
            }
            SPUtils.saveStringData(this, "inform_message", "-1");
        } else if ("article".equals(SPUtils.getStringData(this, "inform_title", "-1"))) {
            SPUtils.saveStringData(this, "inform_title", "-1");
            Intent intent = new Intent(this, WebViewActivity.class);
            intent.putExtra("title", "文章详情");
            intent.putExtra("url", SPUtils.getStringData(this, "inform_message", "-1"));
            startActivity(intent);
        }
        RequestParams params = new RequestParams();
//        params.put("token", token);
        HttpUtils.post(Constants.GET_USER_MSG, params, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                // 输出错误信息
            }

            @Override
            public void onFinish() {
                // 隐藏进度条
                super.onFinish();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                try {
                    JSONObject jsonObject = new JSONObject(responseString);
                    //返回码
                    UserInfoBean userBean = null;
                    int code = jsonObject.optInt("code");
                    //返回码说明
                    String msg = jsonObject.optString("msg");
                    String data = jsonObject.optString("data");
                    if (0 == code) {
                        if (!TextUtils.isEmpty(data)) {//GSON对数字都当做double解析
                            Gson gson = new Gson();
                            userBean = gson.fromJson(data.trim(), UserInfoBean.class);
                            CaiNiaoApplication.setUserInfoBean(userBean);
                        }
                        if (null != userBean) {
                            CaiNiaoApplication.setUserBean(new UserBean(userBean.user_detail.user_id, userBean.user_msg.group_id, SPUtils.getStringData(MainActivity.this, "token", ""), userBean.user_detail.avatar, userBean.user_detail.nickname, userBean.user_msg.is_forever));
                        }
                    } else {
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onStart() {
                super.onStart();
            }
        });
    }

    @Override
    protected void initData() {
        mAcache = ACache.get(this);
        token = mAcache.getAsString(Constants.TOKEN);
        phone = mAcache.getAsString(Constants.ACCOUT);
        pwd = mAcache.getAsString(Constants.PASSWORD);
        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            if (bundle.containsKey("type")) {
                type = bundle.getInt("type");
            }
        }
        fm = getSupportFragmentManager();
        f1 =new HomeFragment();
//        f2 = new KindFragment();
        f2 = new YXFragment();
        f3 = new HkFragment();
        f4 =new CommuitityFragment();
        f5 =new MyFragment();
        ft = fm.beginTransaction();
        switchFragment(f1).commit();
        setStatusBar(getResources().getColor(R.color.colo_3366));

    }
    public FragmentTransaction switchFragment(Fragment targetFragment) {
        FragmentTransaction transaction = getSupportFragmentManager()
                .beginTransaction();
        if (!targetFragment.isAdded()) {
            if (currentFragment != null) {
                transaction.hide(currentFragment);
            }
            transaction.add(R.id.frame, targetFragment, targetFragment.getClass().getName());
        } else {
            transaction
                    .hide(currentFragment)
                    .show(targetFragment);
        }
        currentFragment = targetFragment;
        return transaction;
    }

    @Override
    protected void onStop() {
        super.onStop();
    }
    @Override
    protected void initListener() {
        rg.setOnCheckedChangeListener(new CaiNiaoRadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CaiNiaoRadioGroup group, int checkedId) {

                if (checkedId == R.id.rb_1) {
                    switchFragment(f1).commit();
                    setStatusBar(Color.parseColor(SPUtils.getStringData(MainActivity.this,"color","#333333")));
                } else if (checkedId == R.id.rb_2 || checkedId == R.id.ly_2) {
                    Bundle bundle = new Bundle();
                    bundle.putString("title","悬赏任务");
                    bundle.putString("url",  Constants.APP_IP + "/wap.php/renwu/hall?token=" + SPUtils.getStringData(MainActivity.this, "token", ""));
                    f2.setArguments(bundle);
                    switchFragment(f2).commit();
                    setStatusBar(getResources().getColor(R.color.col_333));
                } else if (checkedId == R.id.rb_3) {
//                    Bundle bundle = new Bundle();
//                    bundle.putString("title","赚咖联盟");
//                    bundle.putString("url", Constants.GET_ZHUANKA_URL);
                    setStatusBar(getResources().getColor(R.color.col_333));
                    Intent intent = new Intent(MainActivity.this, WebViewActivityz.class);
                    intent.putExtra("title", "赚咖联盟");
                    intent.putExtra("url", Constants.GET_ZHUANKA_URL);
                    intent.putExtra("status", "1");
                    startActivity(intent);
//                    f3.setArguments(bundle);
//                    switchFragment(f3).commit();
//                    setStatusBar(getResources().getColor(R.color.col_333));
                } else if (checkedId == R.id.rb_4) {
                    switchFragment(f5).commit();
                    setStatusBar(getResources().getColor(R.color.col_333));
                } else if (checkedId == R.id.rb_5) {
                    switchFragment(f4).commit();
                    setStatusBar(getResources().getColor(R.color.col_333));
                }
            }
        });
    }

    private void getRate() {
        RequestParams params = new RequestParams();
        params.put("token", SPUtils.getStringData(this, "token", ""));
        HttpUtils.post(Constants.GET_RATE, params, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            }

            @Override
            public void onFinish() {
                // 隐藏进度条
                super.onFinish();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                try {
                    JSONObject jsonObject = new JSONObject(responseString);
                    //返回码
                    int code = jsonObject.optInt("code");
                    if (0 == code) {
                        SPUtils.saveIntData(MainActivity.this, "rate", jsonObject.getJSONObject("data").getInt("commission_rate"));


                    } else {
                        T.showShort(MainActivity.this, "登录信息已过期");
                        openActivity(WelActivity.class);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onStart() {
                super.onStart();
            }
        });

    }

    @Subscribe
    public void toHhuiyuan(MessageEvent event) {
        if ("huiyuan".equals(event.getMessage())) {
            ((RadioButton) findViewById(R.id.rb_3)).setChecked(true);
        }else if ("shequ".equals(event.getMessage())) {
            ((RadioButton) findViewById(R.id.rb_5)).setChecked(true);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            Intent intent = new Intent(Intent.ACTION_MAIN);
//            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            intent.addCategory(Intent.CATEGORY_HOME);
//            startActivity(intent);
//            return true;
//        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {
    }

    /**
     * @属性:获取京东推送商品详情
     * @开发者:wmm
     * @时间:2018/12/11 9:50
     */
    private void getJdGoodsMsgRequest(String id) {
        String SERVER_URL = "http://api-gw.haojingke.com/index.php/v1/api/jd/goodsdetail";
        RequestParams params = new RequestParams();
        params.put("apikey",Constants.jd_hjk_appikey);
        params.put("goods_id",id);
        params.put("isdetail",1);
        params.put("isCoupon",1);

        HttpUtils.post(SERVER_URL, params, new TextHttpResponseHandler() {

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {

            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                try {
                    JSONObject data = new JSONObject(responseString);
                    if(data.optInt("status_code") == 200){
                        JdGoodsResp jdGoodsResp =  new Gson().fromJson(String.valueOf(data.getJSONObject("data")),JdGoodsResp.class) ;

                        Intent intent = new Intent(MainActivity.this, JdDetailsActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("goods", jdGoodsResp);
                        intent.putExtra("goods", bundle);
                        startActivity(intent);
                    }else{
                        return;
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
//        String SERVER_URL = "https://router.jd.com/api";
//        String appKey = Constants.jdappKey;
//        String appSecret = Constants.jdclient_secret;
//        String accessToken = "";
//        final JdClient client = new DefaultJdClient(SERVER_URL, accessToken, appKey, appSecret);
//        final UnionOpenGoodsQueryRequest request = new UnionOpenGoodsQueryRequest();
//        final GoodsReq goodsReq = new GoodsReq();
//        goodsReq.setSkuIds(new Long[]{Long.valueOf(id)});
//        goodsReq.setPageSize(6);
//        goodsReq.setPageIndex(1);
//        request.setGoodsReqDTO(goodsReq);
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    UnionOpenGoodsQueryResponse response = client.execute(request);
//                    if (response.getData() == null) {
//                        return;
//                    }
//                    if (response.getData().length <= 0) {
//                        return;
//                    }
//                    Intent intent = new Intent(MainActivity.this, JdDetailsActivity.class);
//                    Bundle bundle = new Bundle();
//                    bundle.putSerializable("goods", response.getData()[0]);
//                    intent.putExtra("goods", bundle);
//                    startActivity(intent);
//                } catch (JdException e) {
//                    e.printStackTrace();
//                }
//            }
//        }).start();
    }

    /**
     * @属性:获取拼多多商品详情
     * @开发者:wmm
     * @时间:2018/12/11 9:50
     */
    private void getPddGoodsMsgRequest(String id) {
        RequestParams requestParams = new RequestParams();
        requestParams.put("goods_id", id);
        HttpUtils.post(Constants.GET_PDD_DETAIL, requestParams, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                showToast(responseString);
            }

            @Override
            public void onFinish() {
                super.onFinish();
                closeLoadingDialog();
            }

            @Override
            public void onStart() {
                super.onStart();
                showLoadingDialog();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                if (getComeActivity().isDestroyed())
                    return;
                try {
                    if (new JSONObject(responseString).getInt("code") != 0) {
                        T.showShort(MainActivity.this, new JSONObject(responseString).getString("msg"));
                        return;
                    }
                    JSONObject object = new JSONObject(responseString).getJSONObject("data");
                    Intent intent = new Intent(MainActivity.this, PddDetailsActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("goods", new Gson().fromJson(object.getJSONObject("goods_details").toString(), PDDBean.class));
                    intent.putExtra("goods", bundle);
                    startActivity(intent);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void showAc(final int posi) {
        if (posi >= adInfos.size()) {
            return;
        }
        List<AdInfo> temp = new ArrayList<>();
        temp.add(adInfos.get(posi));
        if ("8".equals(adInfos.get(posi).getTitle())) {
            isRece(posi);
        } else {
            adManager = new AdManager(MainActivity.this, temp);
            adManager.setOnImageClickListener(new AdManager.OnImageClickListener() {
                @Override
                public void onImageClick(View view, AdInfo advInfo) {
                    Intent intent;
                    switch (advInfo.getTitle()) {
                        case "1":
                            intent = new Intent(MainActivity.this, WebViewActivity.class);
                            intent.putExtra("title", advInfo.getTitle());
                            intent.putExtra("url", advInfo.getUrl());
                            startActivity(intent);
                            break;
                        case "2":
                            intent = getPackageManager().getLaunchIntentForPackage("com.taobao.taobao");
                            if (intent != null) {
                                ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                                ClipData mClipData = ClipData.newPlainText("Label", advInfo.getUrl());
                                cm.setPrimaryClip(mClipData);
                                startActivity(intent);
                                return;
                            } else {
                                T.showShort(MainActivity.this, "未安装淘宝客户端");
                            }
                            break;
                        case "3":
                            break;
                        case "4":
                            break;
                        case "5":
                            break;
                        case "6":
                            intent = new Intent(MainActivity.this, WebViewActivity2.class);
                            intent.putExtra("title", "年货节");
                            intent.putExtra("url", "");
                            startActivity(intent);
                            break;
                        case "7":
                            isRece(posi);
                            return;
                        case "8":
                            isRece(posi);
                            return;
                        case "9":
                            Bundle bundle = new Bundle();
                            bundle.putString("num_iid", advInfo.getUrl());
                            openActivity(PromotionDetailsActivity.class, bundle);
                            break;
                    }
                    adManager.dismissAdDialog();
                    adManager = null;
                    currentAc = currentAc + 1;
                    showAc(currentAc);
                }
            }).setOnCloseClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    adManager = null;
                    currentAc = currentAc + 1;
                    showAc(currentAc);
                }
            });
            adManager.setOverScreen(true)
                    .setPageTransformer(new ZoomOutTranformer()).showAdDialog(AdConstant.ANIM_UP_TO_DOWN);
        }
    }

    private void getActivities() {
        RequestParams requestParams = new RequestParams();
        requestParams.put("cat_id", 5);
        HttpUtils.post(Constants.GET_BANNER, requestParams, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
//                showToast(throwable.getMessage());
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                try {
                    JSONObject object = new JSONObject(responseString);
                    if (object.getInt("code") == 0) {
                        final JSONArray array = object.getJSONObject("data").getJSONArray("list");
                        adInfos.clear();
                        for (int i = 0; i < array.length(); i++) {
                            AdInfo adInfo = new AdInfo();
                            object = array.getJSONObject(i);
                            adInfo.setActivityImg(Constants.APP_IP + object.getString("img"));
                            switch (object.getString("type")) {
                                case "1":
                                    adInfo.setUrl(object.getString("href"));
                                    break;
                                case "2":
                                    adInfo.setUrl(object.getString("type_value"));
                                    break;
                                case "3":
                                    break;
                                case "4":
                                    break;
                                case "5":
                                    break;
                                case "6":
                                    break;
                                case "7":
                                    break;
                                case "8":
                                    break;
                                case "9":
                                    adInfo.setUrl(object.getString("type_value"));
                                    break;
                            }
                            adInfo.setTitle(object.getString("type"));
                            adInfos.add(adInfo);
                        }
                        showAc(currentAc);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void isRece(final int pos) {
        String time = String.valueOf(System.currentTimeMillis() / 1000);
        RequestParams requestParams = new RequestParams();
        requestParams.put("data_type", PddClient.data_type);
        requestParams.put("version", PddClient.version);
        requestParams.put("timestamp", time);
        requestParams.put("token", SPUtils.getStringData(this, "token", ""));
        requestParams.put("type", "hkx.UserBalanceRecord.isReceiveBonus");
        Map<String, String> temp = new HashMap<>();
        temp.put("data_type", PddClient.data_type);
        temp.put("version", PddClient.version);
        temp.put("timestamp", time);
        temp.put("token", SPUtils.getStringData(this, "token", ""));
        temp.put("type", "hkx.UserBalanceRecord.isReceiveBonus");
        String sign = PddClient.getSign1(temp);
        requestParams.put("sign", sign);
        HttpUtils.post(Constants.ISRECEIVER_BONUS, requestParams, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {

            }

            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                try {
                    JSONObject jsonObject = new JSONObject(responseString);
                    if ("N".equals(jsonObject.getJSONObject("data").getString("is_receive"))) {
                        List<AdInfo> temp = new ArrayList<>();
                        temp.add(adInfos.get(pos));
                        adManager = new AdManager(MainActivity.this, temp);
                        adManager.setOnImageClickListener(new AdManager.OnImageClickListener() {
                            @Override
                            public void onImageClick(View view, AdInfo advInfo) {
                                hongbao();
//                                        Intent intent = new Intent(MainActivity.this, WebViewActivity2.class);
//                                        intent.putExtra("title", "年货节");
//                                        intent.putExtra("url", "");
//                                        startActivity(intent);
                                adManager.dismissAdDialog();
                                adManager = null;
                                currentAc = currentAc + 1;
                                showAc(currentAc);
                            }
                        }).setOnCloseClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                adManager = null;
                                currentAc = currentAc + 1;
                                showAc(currentAc);
                            }
                        });
                        adManager.setOverScreen(true)
                                .setPageTransformer(new ZoomOutTranformer()).showAdDialog(AdConstant.ANIM_UP_TO_DOWN);
                    } else {
                        currentAc = currentAc + 1;
                        showAc(currentAc);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void hongbao() {
        String time = String.valueOf(System.currentTimeMillis() / 1000);
        RequestParams requestParams = new RequestParams();
        requestParams.put("data_type", PddClient.data_type);
        requestParams.put("version", PddClient.version);
        requestParams.put("timestamp", time);
        requestParams.put("token", SPUtils.getStringData(this, "token", ""));
        requestParams.put("type", "hkx.UserBalanceRecord.receiveBonus");
        Map<String, String> temp = new HashMap<>();
        temp.put("data_type", PddClient.data_type);
        temp.put("version", PddClient.version);
        temp.put("timestamp", time);
        temp.put("token", SPUtils.getStringData(this, "token", ""));
        temp.put("type", "hkx.UserBalanceRecord.receiveBonus");
        String sign = PddClient.getSign1(temp);
        requestParams.put("sign", sign);
        HttpUtils.post(Constants.HONGBAO, requestParams, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {

            }

            @Override
            public void onStart() {
                super.onStart();
                showLoadingDialog();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                closeLoadingDialog();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                try {
                    JSONObject jsonObject = new JSONObject(responseString);
                    int code = jsonObject.optInt("code");
                    String msg = jsonObject.optString("msg");
                    Intent intent = new Intent(MainActivity.this, QdActivity.class);
                    intent.putExtra("money", jsonObject.getString("money"));
                    SPUtils.saveIntData(MainActivity.this, "hongbao", 1);
                    if (code == 0) {
                        intent.putExtra("mess", "新年红包已存至余额~");
                    } else {
                        intent.putExtra("mess", msg);
                    }
                    startActivity(intent);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
